//
//  BossScene.m
//  iFly
//
//  Created by User-10 on 12/13/14.
//  Copyright (c) 2014 TeamDifferent. All rights reserved.
//

#import "BossScene.h"
#import "Constants.h"
#import "CharacterNode.h"
#import "EnemyCharacterNode.h"
#import "EnemyFactory.h"
#import "EnemyNode.h"

#import "FMMParallaxNode.h"
#import "PauseButton.h"
#import "FireButtonNode.h"
#import "ShieldButtonNode.h"

#import "ProjectileFactory.h"
#import "ProjectileNode.h"

#import "BonusFactory.h"
#import "BonusNode.h"

#import "Joystick.h"

#import "ContactHandler.h"
#import "SoundHandler.h"



@interface BossScene ()

@property NSTimeInterval lastUpdatedTime;
@property NSTimeInterval deltaTime;
@property NSTimeInterval lastBonusAdded;

@end

@implementation BossScene {
    CharacterNode* character;
    EnemyCharacterNode* enemyCharacter;
    PauseButton* pauseButton;
    Joystick* joystick;
    SKLabelNode* scoreLabelNode;
    
    float scaleCoef;
    
    FMMParallaxNode *_parallaxNodeBackgrounds;
    FMMParallaxNode *_parallaxSpaceDust;
    FMMParallaxNode *_parallaxMoon;
    FireButtonNode *fireButton;
    ShieldButtonNode *shieldButton;
    SKSpriteNode* background;
    NSInteger previousScore;
    BOOL isStageStarted;
}

-(id)initWithSize:(CGSize)size andScore:(NSInteger) score {
    if (self = [super initWithSize:size]) {
        
        scaleCoef= size.height/sceneScaling;
        previousScore = score;
        isStageStarted = NO;
        
        //playing background music
        [[SoundHandler sharedSoundPlayer] playBackgroundMusicWithURL:@"IronManSong" andExtension:@"mp3"];
        
        self.backgroundColor = [SKColor lightGrayColor];
        
#pragma mark - Game backgrounds
        
        
        NSArray* parallaxOne = @[@"bg_half-moon.png"];
        CGSize moonSize = CGSizeMake(100.0, 100.0);
        _parallaxMoon = [[FMMParallaxNode alloc]initWithBackgrounds:parallaxOne size:moonSize pointsPerSecondSpeed:100.0];
        _parallaxMoon.position = CGPointMake(moonPosition, self.size.height/1.35);
        [self addChild:_parallaxMoon];
        
        //Bring on the space dust
        NSArray *parallaxBackground2Names = @[@"bg_front_spacedust.png",@"bg_front_spacedust.png"];
        _parallaxSpaceDust = [[FMMParallaxNode alloc] initWithBackgrounds:parallaxBackground2Names
                                                                     size:size pointsPerSecondSpeed:25.0];
        _parallaxSpaceDust.position = CGPointMake(0, 0);
        [self addChild:_parallaxSpaceDust];
        
        pauseButton=[PauseButton pauseButtonWithPosition:CGPointMake(100, 100) inScene:self];
        [self addChild:pauseButton];
        pauseButton.name=@"pause";
        
        
        [[UIApplication sharedApplication] delegate];
        [[NSNotificationCenter defaultCenter] addObserver:pauseButton selector:@selector(handlePause) name:UIApplicationWillResignActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:pauseButton selector:@selector(handlePause) name:UIApplicationDidBecomeActiveNotification object:nil];
        
        
        self.physicsWorld.contactDelegate = self;
    }
    return self;
}

-(void)didMoveToView:(SKView *)view {
    //adding character and health bar
    [self addHealthBar];
    character = [CharacterNode characterWithPosition:CGPointMake(characterXPosition, self.frame.size.height/2) inScene:self];
    [character setScale:scaleCoef];
    [character initialSetLives:self.initialLives];
    [self addChild:character];
    
    //setting loki picture at start
    SKSpriteNode* lokiUpcoming = [SKSpriteNode spriteNodeWithImageNamed:@"lokiUpcoming.png"];
    [lokiUpcoming setScale:self.size.height/640];
    lokiUpcoming.position = CGPointMake(self.size.width/2,lokiUpcoming.size.height/2);
    [self addChild:lokiUpcoming];
    
    SKAction* laugh = [SKAction runBlock:^{
        [[SoundHandler sharedSoundPlayer] playSoundWithName:@"evilLaugh" andType:@"mp3"];
    }];
    SKAction* wait = [SKAction waitForDuration:3];
    SKAction* fadeOut = [SKAction fadeAlphaTo:0.0 duration:1];
    SKAction* activateHud = [SKAction runBlock:^{
        
        //adding joystick
        joystick = [Joystick joystick];
        [self addChild:joystick];
        joystick.position = CGPointMake(self.scene.frame.origin.x+joystickOffset*scaleCoef, self.scene.frame.origin.y+joystickOffset*scaleCoef);
        joystick.name = @"joystick";
        [joystick setScale:scaleCoef*joystickScalling];
        
        fireButton = [FireButtonNode fireButtonOnPosition:CGPointMake(self.scene.size.width-fireButtonOffset*scaleCoef, fireButtonOffset*scaleCoef) inScene:self];
        [fireButton setScale:scaleCoef*fireButtonScaling];
        [self addChild:fireButton];
        
        shieldButton = [ShieldButtonNode shieldButtonOnPosition:CGPointMake(self.scene.size.width-fireButtonOffset*scaleCoef - fireButton.size.width - shieldButtonOffset*scaleCoef, fireButtonOffset*scaleCoef) inScene:self];
        [shieldButton setScale:scaleCoef*fireButtonScaling ];
        [self addChild:shieldButton];
        
        scoreLabelNode=[ Constants createLabelWithFont:labelFontName text:@"Score: 0" fontColor:[UIColor whiteColor] fontSize:25];
        scoreLabelNode.position=CGPointMake(self.scene.size.width/2,self.scene.size.height - buttonsOffset);
        scoreLabelNode.name=@"score";
        [self addChild:scoreLabelNode];
        
        [character addScore:previousScore];
        
    }];
    
    //loki flies in
    SKAction* enemyFliesIn = [SKAction runBlock:^{
        enemyCharacter = [EnemyCharacterNode enemyCharacterWithPosition:CGPointMake(self.size.width+flyingInOffset ,self.size.height/2) inScene:self];
        [enemyCharacter setScale:scaleCoef];
        [self addChild:enemyCharacter];
        [enemyCharacter flyIn];
    }];
    
    
    SKAction* sequence = [SKAction sequence:@[laugh,wait,fadeOut]];
    [lokiUpcoming runAction:sequence completion:^{
        [self runAction:activateHud completion:^{
            [self runAction:enemyFliesIn];
            isStageStarted = YES;
        }];
    }];

    
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch* touch= [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode* touchedNode=[self nodeAtPoint:location];
    
    if (touchedNode== pauseButton) {;
        
        if (pauseButton.isGamePaused == NO) {
            [[SoundHandler sharedSoundPlayer] pauseBackgroundMusic];
            [pauseButton handlePause];
            //if game is paused invalidate current timer
        }
        else {
            [[SoundHandler sharedSoundPlayer] resumeBackgroundMusic];
            [pauseButton handleUnPause];
        }
    }
    SKNode* currentNode = [self nodeAtPoint:location];
    
    if ([currentNode.name  isEqual: @"fire"]) {
        [fireButton fire];
        return;
    }
    
    if([currentNode.name isEqual:@"shield"]){
        [shieldButton activateShield];
    }
    
}

//detecting contact between nodes;
- (void)didBeginContact:(SKPhysicsContact *)contact {
    SKPhysicsBody *firstBody, *secondBody;
    
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
    {
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    }
    else
    {
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }
    [ContactHandler contactBetweenNodeA:(SKSpriteNode*)firstBody.node andNodeB:(SKSpriteNode*)secondBody.node];
}

-(void)addCoin {
    //initializing coin
    BonusNode* coin = [BonusFactory createBonusWithType:BonusTypeCoin inScene:self];
    if (coin) {
        SKAction* rotate= [SKAction rotateByAngle:M_PI duration:1.0];
        SKAction* repeatedRotation=[SKAction repeatActionForever:rotate];
        [coin runAction:repeatedRotation];
        [coin setScale:scaleCoef/coinScaling];
        
        [self addChild:coin];
        
    }
}
-(void) addHealthBar {
    SKSpriteNode* healthBar=[SKSpriteNode spriteNodeWithImageNamed:[NSString stringWithFormat:@"HealthBar%ld",(long)self.initialLives]];
    [healthBar setScale:scaleCoef/2];
    healthBar.position=CGPointMake(buttonsOffset + healthBar.size.width/3, self.scene.size.height - buttonsOffset*scaleCoef);
    healthBar.name=@"healthBar";
    healthBar.zPosition=1;
    [self addChild:healthBar];

}

-(void)update:(CFTimeInterval)currentTime {
    //if game is paused do not update
    [character setScale:scaleCoef];
    if (self.paused) {
        return;
    }
    if (self.lastUpdatedTime) {
        self.deltaTime=currentTime - self.lastUpdatedTime;
    }
    else {
        self.deltaTime =0;
    }
    self.lastUpdatedTime=currentTime;
    
    //adding bonuses
    if(currentTime - self.lastBonusAdded > 1 && isStageStarted){
        self.lastBonusAdded = currentTime + 3;
        [self addCoin];

    }
    
    //Update background (parallax) position
    [_parallaxSpaceDust update:currentTime];
    [_parallaxNodeBackgrounds update:currentTime];
    pauseButton.isParalaxPaused = NO;
}

@end
